/** @file         client.c
 *  @brief        简要说明
 *  @details      详细说明
 *  @author       lzm
 *  @date         2021-06-10 09:49:46
 *  @version      v1.0
 *  @copyright    Copyright By lizhuming, All Rights Reserved
 *  @blog         https://www.cnblogs.com/lizhuming/
 **********************************************************
 *  @LOG 修改日志:
 **********************************************************
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

#define TCPC_CFG_HOST_ADDRESS_DEFAULT "127.0.0.1" // default remote server address
#define TCPC_CFG_HOST_PORT_DEFAULT 9998    
#define BUFFER_MAX_SIZE (1*1024)   // max buffer size

/**
  * @brief  main
  * @param 
  * @retval 
  * @author
  */
int main(void)
{
    int sockfd = 0;
    int ret = 0;
    struct sockaddr_in server = {0};
    char data_buffer[BUFFER_MAX_SIZE] = {0};

    struct addrinfo hints;
	memset(&hints, 0, sizeof(hints));
	hints.ai_family   = AF_INET6;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags    = AI_ADDRCONFIG;

    /* [1] Create a socket */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd == -1)
    {
        printf("creat socket failed!\n");
        exit(1);
    }

    /* [2] Initial address */
    memset(&server, 0x00, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(TCPC_CFG_HOST_PORT_DEFAULT);
    server.sin_addr.s_addr = inet_addr(TCPC_CFG_HOST_ADDRESS_DEFAULT);

    /* [3] establishing a TCP connection */
    ret = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
    if(ret < 0)
    {
        printf("connect server failed![%d]\n", errno);
        close(sockfd);
        exit(1);
    }

    printf("connect server success!");

    /* [4] enter loop */
    while(1)
    {
        printf("please enter some text:");
        fgets(data_buffer, BUFFER_MAX_SIZE, stdin);

        // input end:exit a loop
        if(strncmp(data_buffer, "end", 3) == 0)
            break;

        send(sockfd, data_buffer, sizeof(data_buffer), 0);

        bzero(data_buffer, sizeof(data_buffer));

        recv(sockfd, data_buffer, sizeof(data_buffer), 0);

        printf("recv data:%s\r\n", data_buffer);

    }

    /* [5] exit */
    close(sockfd);
    exit(0);
}
